/**
 * 富文本编辑器组件
 * Rich Text Editor Component
 */

class RichEditor {
  constructor(container, options = {}) {
    this.container = typeof container === 'string' ? document.querySelector(container) : container;
    this.options = {
      placeholder: '开始写作...',
      autoSave: true,
      autoSaveInterval: 3000, // 3秒自动保存
      maxLength: 50000, // 最大字符数
      toolbar: ['bold', 'italic', 'underline', 'strikethrough', 'h1', 'h2', 'h3', 'ul', 'ol', 'link', 'image'],
      ...options
    };
    
    this.editor = null;
    this.toolbar = null;
    this.content = '';
    this.autoSaveTimer = null;
    this.isComposing = false; // 中文输入状态
    this.history = [];
    this.historyIndex = -1;
    this.maxHistory = 50;
    
    this.init();
  }

  /**
   * 初始化编辑器
   */
  init() {
    if (!this.container) {
      console.error('Rich Editor: Container not found');
      return;
    }

    this.createEditor();
    this.createToolbar();
    this.bindEvents();
    this.setupKeyboardShortcuts();
    
    if (this.options.autoSave) {
      this.startAutoSave();
    }
  }

  /**
   * 创建编辑器
   */
  createEditor() {
    this.container.innerHTML = `
      <div class="rich-editor bg-white border border-neutral-200 rounded-lg overflow-hidden">
        <!-- 工具栏 -->
        <div id="editor-toolbar" class="border-b border-neutral-200 bg-neutral-50 p-2 flex flex-wrap gap-1">
          <!-- 工具栏按钮将通过 createToolbar 方法生成 -->
        </div>
        
        <!-- 编辑区域 -->
        <div class="relative">
          <div 
            id="editor-content"
            class="min-h-[300px] p-4 focus:outline-none"
            contenteditable="true"
            data-placeholder="${this.options.placeholder}"
            style="max-height: 500px; overflow-y: auto;"
          ></div>
          
          <!-- 字符计数 -->
          <div class="absolute bottom-2 right-2 text-xs text-neutral-400 bg-white px-2 py-1 rounded shadow-sm">
            <span id="char-count">0</span> / ${this.options.maxLength}
          </div>
        </div>
        
        <!-- 状态栏 -->
        <div class="border-t border-neutral-200 bg-neutral-50 px-4 py-2 flex items-center justify-between text-xs text-neutral-500">
          <div class="flex items-center gap-4">
            <span id="editor-status">就绪</span>
            <span id="word-count">0 字</span>
          </div>
          <div class="flex items-center gap-2">
            <span id="auto-save-status" class="hidden">
              <i class="fa fa-check text-green-500"></i>
              已保存
            </span>
          </div>
        </div>
      </div>
    `;

    this.editor = this.container.querySelector('#editor-content');
    this.toolbar = this.container.querySelector('#editor-toolbar');
    
    // 设置占位符样式
    this.updatePlaceholder();
  }

  /**
   * 创建工具栏
   */
  createToolbar() {
    const toolbarButtons = {
      bold: { icon: 'fa-bold', title: '粗体 (Ctrl+B)', command: 'bold' },
      italic: { icon: 'fa-italic', title: '斜体 (Ctrl+I)', command: 'italic' },
      underline: { icon: 'fa-underline', title: '下划线 (Ctrl+U)', command: 'underline' },
      strikethrough: { icon: 'fa-strikethrough', title: '删除线', command: 'strikeThrough' },
      h1: { icon: 'fa-header', title: '标题1', command: 'formatBlock', value: 'h1', text: 'H1' },
      h2: { icon: 'fa-header', title: '标题2', command: 'formatBlock', value: 'h2', text: 'H2' },
      h3: { icon: 'fa-header', title: '标题3', command: 'formatBlock', value: 'h3', text: 'H3' },
      ul: { icon: 'fa-list-ul', title: '无序列表', command: 'insertUnorderedList' },
      ol: { icon: 'fa-list-ol', title: '有序列表', command: 'insertOrderedList' },
      link: { icon: 'fa-link', title: '插入链接', command: 'createLink' },
      image: { icon: 'fa-image', title: '插入图片', command: 'insertImage' },
      video: { icon: 'fa-video-camera', title: '插入视频', command: 'insertVideo' },
      audio: { icon: 'fa-music', title: '插入音频', command: 'insertAudio' },
      handwriting: { icon: 'fa-pencil-square-o', title: '手写', command: 'insertHandwriting' },
      emoji: { icon: 'fa-smile-o', title: '表情符号', command: 'insertEmoji' }
    };

    let toolbarHTML = '';
    
    this.options.toolbar.forEach((tool, index) => {
      if (tool === '|') {
        toolbarHTML += '<div class="w-px h-6 bg-neutral-300 mx-1"></div>';
        return;
      }
      
      const button = toolbarButtons[tool];
      if (!button) return;
      
      const isHeader = ['h1', 'h2', 'h3'].includes(tool);
      
      toolbarHTML += `
        <button 
          type="button"
          class="toolbar-btn flex items-center justify-center w-8 h-8 rounded hover:bg-neutral-200 transition-colors ${isHeader ? 'text-xs font-bold' : ''}"
          data-command="${button.command}"
          ${button.value ? `data-value="${button.value}"` : ''}
          title="${button.title}"
        >
          ${button.text ? button.text : `<i class="fa ${button.icon}"></i>`}
        </button>
      `;
    });

    this.toolbar.innerHTML = toolbarHTML;
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 工具栏按钮点击
    this.toolbar.addEventListener('click', (e) => {
      const btn = e.target.closest('.toolbar-btn');
      if (!btn) return;
      
      e.preventDefault();
      this.executeCommand(btn.dataset.command, btn.dataset.value);
    });

    // 编辑器内容变化
    this.editor.addEventListener('input', (e) => {
      if (!this.isComposing) {
        this.handleContentChange();
      }
    });

    // 中文输入处理
    this.editor.addEventListener('compositionstart', () => {
      this.isComposing = true;
    });

    this.editor.addEventListener('compositionend', () => {
      this.isComposing = false;
      this.handleContentChange();
    });

    // 焦点事件
    this.editor.addEventListener('focus', () => {
      this.updatePlaceholder();
      this.updateStatus('编辑中...');
    });

    this.editor.addEventListener('blur', () => {
      this.updatePlaceholder();
      this.updateStatus('就绪');
      this.saveToHistory();
    });

    // 选择变化 - 更新工具栏状态
    document.addEventListener('selectionchange', () => {
      if (this.editor.contains(document.getSelection().anchorNode)) {
        this.updateToolbarState();
      }
    });

    // 粘贴事件 - 清理格式
    this.editor.addEventListener('paste', (e) => {
      e.preventDefault();
      const text = e.clipboardData.getData('text/plain');
      this.insertText(text);
    });

    // 拖拽事件
    this.editor.addEventListener('dragover', (e) => {
      e.preventDefault();
      this.editor.classList.add('drag-over');
    });

    this.editor.addEventListener('dragleave', (e) => {
      e.preventDefault();
      this.editor.classList.remove('drag-over');
    });

    this.editor.addEventListener('drop', (e) => {
      e.preventDefault();
      this.editor.classList.remove('drag-over');
      this.handleFileDrop(e.dataTransfer.files);
    });
  }

  /**
   * 设置键盘快捷键
   */
  setupKeyboardShortcuts() {
    this.editor.addEventListener('keydown', (e) => {
      // Ctrl/Cmd + 快捷键
      if (e.ctrlKey || e.metaKey) {
        switch (e.key.toLowerCase()) {
          case 'b':
            e.preventDefault();
            this.executeCommand('bold');
            break;
          case 'i':
            e.preventDefault();
            this.executeCommand('italic');
            break;
          case 'u':
            e.preventDefault();
            this.executeCommand('underline');
            break;
          case 's':
            e.preventDefault();
            this.save();
            break;
          case 'z':
            e.preventDefault();
            if (e.shiftKey) {
              this.redo();
            } else {
              this.undo();
            }
            break;
          case 'y':
            e.preventDefault();
            this.redo();
            break;
        }
      }

      // Tab 键处理
      if (e.key === 'Tab') {
        e.preventDefault();
        this.insertText('    '); // 插入4个空格
      }

      // Enter 键处理
      if (e.key === 'Enter') {
        // 在列表中按Enter时的特殊处理
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        const listItem = range.startContainer.closest ? range.startContainer.closest('li') : null;
        
        if (listItem && listItem.textContent.trim() === '') {
          e.preventDefault();
          this.executeCommand('outdent');
        }
      }
    });
  }

  /**
   * 执行编辑命令
   */
  executeCommand(command, value = null) {
    this.editor.focus();
    
    try {
      switch (command) {
        case 'createLink':
          this.insertLink();
          break;
        case 'insertImage':
          this.insertImage();
          break;
        case 'insertVideo':
          this.insertVideo();
          break;
        case 'insertAudio':
          this.insertAudio();
          break;
        case 'insertHandwriting':
          this.insertHandwriting();
          break;
        case 'insertEmoji':
          this.insertEmoji();
          break;
        default:
          document.execCommand(command, false, value);
          break;
      }
      
      this.handleContentChange();
      this.updateToolbarState();
    } catch (error) {
      console.error('执行编辑命令失败:', error);
    }
  }

  /**
   * 插入链接
   */
  insertLink() {
    const selection = window.getSelection();
    const selectedText = selection.toString();
    
    const url = prompt('请输入链接地址:', 'https://');
    if (!url) return;
    
    if (selectedText) {
      document.execCommand('createLink', false, url);
    } else {
      const linkText = prompt('请输入链接文本:', url);
      if (linkText) {
        this.insertHTML(`<a href="${url}" target="_blank">${linkText}</a>`);
      }
    }
  }

  /**
   * 插入图片
   */
  insertImage() {
    this.showMediaInsertModal('image');
  }

  /**
   * 插入视频
   */
  insertVideo() {
    this.showMediaInsertModal('video');
  }

  /**
   * 插入音频
   */
  insertAudio() {
    this.showMediaInsertModal('audio');
  }

  /**
   * 插入手写
   */
  insertHandwriting() {
    this.showHandwritingModal();
  }

  /**
   * 显示手写模态框
   */
  showHandwritingModal() {
    const modal = this.createHandwritingModal();
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
      modal.classList.remove('opacity-0');
      modal.querySelector('.modal-content').classList.remove('scale-95');
    }, 10);
  }

  /**
   * 创建手写模态框
   */
  createHandwritingModal() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 opacity-0 transition-opacity duration-300';
    
    modal.innerHTML = `
      <div class="modal-content bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-hidden transform scale-95 transition-transform duration-300">
        <div class="flex items-center justify-between p-4 border-b border-neutral-200">
          <h3 class="text-lg font-semibold text-neutral-800 flex items-center gap-2">
            <i class="fa fa-pencil-square-o text-primary"></i>
            手写板
          </h3>
          <button class="close-handwriting-modal text-neutral-400 hover:text-neutral-600">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="p-4">
          <div id="handwriting-canvas-container"></div>
        </div>
        
        <div class="border-t border-neutral-200 p-4 flex justify-end gap-2">
          <button class="close-handwriting-modal btn-secondary">取消</button>
        </div>
      </div>
    `;
    
    this.bindHandwritingModalEvents(modal);
    return modal;
  }

  /**
   * 绑定手写模态框事件
   */
  bindHandwritingModalEvents(modal) {
    const canvasContainer = modal.querySelector('#handwriting-canvas-container');
    
    // 初始化手写板
    const drawingCanvas = new DrawingCanvas(canvasContainer, {
      width: 800,
      height: 400,
      onInsert: async (data) => {
        try {
          // 将手写内容插入到编辑器
          await this.insertHandwritingContent(data.blob);
          closeModal();
        } catch (error) {
          console.error('插入手写内容失败:', error);
          notification.error('插入手写内容失败');
        }
      }
    });
    
    // 关闭模态框
    const closeModal = () => {
      modal.classList.add('opacity-0');
      modal.querySelector('.modal-content').classList.add('scale-95');
      setTimeout(() => {
        if (modal.parentNode) {
          drawingCanvas.destroy();
          modal.parentNode.removeChild(modal);
        }
      }, 300);
    };
    
    modal.querySelectorAll('.close-handwriting-modal').forEach(btn => {
      btn.addEventListener('click', closeModal);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeModal();
      }
    });
  }

  /**
   * 插入手写内容
   */
  async insertHandwritingContent(blob) {
    try {
      this.updateStatus('处理手写内容...');
      
      // 如果有媒体上传器，使用它上传
      if (this.mediaUploader) {
        // 创建File对象
        const file = new File([blob], `handwriting_${Date.now()}.webp`, {
          type: 'image/webp',
          lastModified: Date.now()
        });
        
        const result = await this.mediaUploader.uploadFile(file);
        
        // 插入手写图片
        this.insertHTML(`
          <figure class="media-figure handwriting-figure">
            <img src="${result.url}" alt="手写内容" style="max-width: 100%; height: auto; border-radius: 0.375rem; border: 1px solid #e5e7eb;">
            <figcaption class="text-sm text-neutral-500 text-center mt-2">手写内容</figcaption>
          </figure>
        `);
        
        this.updateStatus('手写内容插入成功');
        notification.success('手写内容插入成功');
        
      } else {
        // 如果没有上传器，使用DataURL
        const reader = new FileReader();
        reader.onload = (e) => {
          this.insertHTML(`
            <figure class="media-figure handwriting-figure">
              <img src="${e.target.result}" alt="手写内容" style="max-width: 100%; height: auto; border-radius: 0.375rem; border: 1px solid #e5e7eb;">
              <figcaption class="text-sm text-neutral-500 text-center mt-2">手写内容</figcaption>
            </figure>
          `);
          
          this.updateStatus('手写内容插入成功');
          notification.success('手写内容插入成功');
        };
        reader.readAsDataURL(blob);
      }
      
    } catch (error) {
      console.error('插入手写内容失败:', error);
      this.updateStatus('插入失败');
      throw error;
    }
  }

  /**
   * 插入表情符号
   */
  insertEmoji() {
    this.showEmojiPicker();
  }

  /**
   * 显示表情选择器
   */
  showEmojiPicker() {
    // 如果已经有表情选择器，直接显示
    if (this.emojiPickerModal) {
      this.emojiPickerModal.classList.remove('hidden');
      return;
    }

    // 创建表情选择器模态框
    this.emojiPickerModal = this.createEmojiPickerModal();
    document.body.appendChild(this.emojiPickerModal);
    
    // 显示模态框
    setTimeout(() => {
      this.emojiPickerModal.classList.remove('opacity-0');
    }, 10);
  }

  /**
   * 创建表情选择器模态框
   */
  createEmojiPickerModal() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50 opacity-0 transition-opacity duration-300';
    
    modal.innerHTML = `
      <div class="emoji-picker-modal bg-white rounded-lg shadow-xl">
        <div id="emoji-picker-container"></div>
      </div>
    `;
    
    this.bindEmojiPickerEvents(modal);
    return modal;
  }

  /**
   * 绑定表情选择器事件
   */
  bindEmojiPickerEvents(modal) {
    const container = modal.querySelector('#emoji-picker-container');
    
    // 初始化表情选择器
    this.emojiPicker = new EmojiPicker(container, {
      onSelect: (emoji) => {
        this.insertEmojiToEditor(emoji);
        this.hideEmojiPicker();
      }
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        this.hideEmojiPicker();
      }
    });
    
    // ESC键关闭
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') {
        this.hideEmojiPicker();
        document.removeEventListener('keydown', handleKeyDown);
      }
    };
    document.addEventListener('keydown', handleKeyDown);
  }

  /**
   * 插入表情到编辑器
   */
  insertEmojiToEditor(emoji) {
    // 保存当前光标位置
    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      
      // 创建表情元素
      const emojiSpan = document.createElement('span');
      emojiSpan.textContent = emoji;
      emojiSpan.className = 'emoji';
      emojiSpan.style.fontSize = '1.2em';
      
      // 插入表情
      range.deleteContents();
      range.insertNode(emojiSpan);
      
      // 移动光标到表情后面
      range.setStartAfter(emojiSpan);
      range.collapse(true);
      selection.removeAllRanges();
      selection.addRange(range);
      
      // 触发内容变化
      this.handleContentChange();
      
      this.updateStatus('表情插入成功');
    }
  }

  /**
   * 隐藏表情选择器
   */
  hideEmojiPicker() {
    if (this.emojiPickerModal) {
      this.emojiPickerModal.classList.add('opacity-0');
      setTimeout(() => {
        if (this.emojiPickerModal && this.emojiPickerModal.parentNode) {
          this.emojiPickerModal.parentNode.removeChild(this.emojiPickerModal);
          this.emojiPickerModal = null;
          this.emojiPicker = null;
        }
      }, 300);
    }
  }

  /**
   * 显示媒体插入模态框
   */
  showMediaInsertModal(type) {
    const modal = this.createMediaInsertModal(type);
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
      modal.classList.remove('opacity-0');
      modal.querySelector('.modal-content').classList.remove('scale-95');
    }, 10);
  }

  /**
   * 创建媒体插入模态框
   */
  createMediaInsertModal(type) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 opacity-0 transition-opacity duration-300';
    
    const typeConfig = {
      image: {
        title: '插入图片',
        accept: 'image/*',
        icon: 'fa-image',
        maxSize: '5MB',
        formats: 'JPG, PNG, WebP'
      },
      video: {
        title: '插入视频',
        accept: 'video/*',
        icon: 'fa-video-camera',
        maxSize: '50MB',
        formats: 'MP4, WebM'
      },
      audio: {
        title: '插入音频',
        accept: 'audio/*',
        icon: 'fa-music',
        maxSize: '10MB',
        formats: 'MP3, WAV'
      }
    };
    
    const config = typeConfig[type];
    
    modal.innerHTML = `
      <div class="modal-content bg-white rounded-lg shadow-xl max-w-md w-full mx-4 transform scale-95 transition-transform duration-300">
        <div class="flex items-center justify-between p-4 border-b border-neutral-200">
          <h3 class="text-lg font-semibold text-neutral-800 flex items-center gap-2">
            <i class="fa ${config.icon} text-primary"></i>
            ${config.title}
          </h3>
          <button class="close-modal text-neutral-400 hover:text-neutral-600">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="p-6">
          <!-- 拖拽上传区域 -->
          <div class="upload-area border-2 border-dashed border-neutral-300 rounded-lg p-8 text-center hover:border-primary transition-colors cursor-pointer">
            <i class="fa ${config.icon} text-4xl text-neutral-400 mb-4"></i>
            <p class="text-neutral-600 mb-2">拖拽文件到此处或点击选择</p>
            <p class="text-sm text-neutral-400">支持格式: ${config.formats}</p>
            <p class="text-sm text-neutral-400">最大大小: ${config.maxSize}</p>
            <input type="file" class="file-input hidden" accept="${config.accept}" ${type === 'image' ? 'multiple' : ''}>
          </div>
          
          <!-- 上传进度区域 -->
          <div class="upload-progress-container mt-4 hidden">
            <h4 class="text-sm font-medium text-neutral-700 mb-2">上传进度</h4>
            <div class="progress-list max-h-32 overflow-y-auto"></div>
          </div>
          
          <!-- URL输入选项 -->
          <div class="mt-4 pt-4 border-t border-neutral-200">
            <label class="block text-sm font-medium text-neutral-700 mb-2">或输入${config.title.slice(2)}链接</label>
            <div class="flex gap-2">
              <input type="url" class="url-input flex-1 px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="https://...">
              <button class="insert-url-btn btn-primary">插入</button>
            </div>
          </div>
        </div>
        
        <div class="border-t border-neutral-200 p-4 flex justify-end gap-2">
          <button class="close-modal btn-secondary">取消</button>
        </div>
      </div>
    `;
    
    this.bindMediaModalEvents(modal, type);
    return modal;
  }

  /**
   * 绑定媒体模态框事件
   */
  bindMediaModalEvents(modal, type) {
    const uploadArea = modal.querySelector('.upload-area');
    const fileInput = modal.querySelector('.file-input');
    const urlInput = modal.querySelector('.url-input');
    const insertUrlBtn = modal.querySelector('.insert-url-btn');
    const progressContainer = modal.querySelector('.upload-progress-container');
    const progressList = modal.querySelector('.progress-list');
    
    // 初始化媒体上传器
    if (!this.mediaUploader) {
      this.mediaUploader = new MediaUploader();
    }
    
    // 关闭模态框
    const closeModal = () => {
      modal.classList.add('opacity-0');
      modal.querySelector('.modal-content').classList.add('scale-95');
      setTimeout(() => {
        if (modal.parentNode) {
          modal.parentNode.removeChild(modal);
        }
      }, 300);
    };
    
    modal.querySelectorAll('.close-modal').forEach(btn => {
      btn.addEventListener('click', closeModal);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeModal();
      }
    });
    
    // 文件选择
    uploadArea.addEventListener('click', () => {
      fileInput.click();
    });
    
    fileInput.addEventListener('change', (e) => {
      this.handleFileUpload(e.target.files, type, progressContainer, progressList, closeModal);
    });
    
    // 拖拽上传
    uploadArea.addEventListener('dragover', (e) => {
      e.preventDefault();
      uploadArea.classList.add('border-primary', 'bg-primary/5');
    });
    
    uploadArea.addEventListener('dragleave', (e) => {
      e.preventDefault();
      uploadArea.classList.remove('border-primary', 'bg-primary/5');
    });
    
    uploadArea.addEventListener('drop', (e) => {
      e.preventDefault();
      uploadArea.classList.remove('border-primary', 'bg-primary/5');
      this.handleFileUpload(e.dataTransfer.files, type, progressContainer, progressList, closeModal);
    });
    
    // URL插入
    insertUrlBtn.addEventListener('click', () => {
      const url = urlInput.value.trim();
      if (url) {
        this.insertMediaFromUrl(url, type);
        closeModal();
      }
    });
    
    urlInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        insertUrlBtn.click();
      }
    });
  }

  /**
   * 处理文件上传
   */
  async handleFileUpload(files, type, progressContainer, progressList, closeModal) {
    if (files.length === 0) return;
    
    progressContainer.classList.remove('hidden');
    
    const fileArray = Array.from(files);
    
    try {
      const results = await this.mediaUploader.uploadFiles(
        fileArray,
        (overallProgress, file, fileProgress) => {
          // 更新整体进度
        },
        (result, error) => {
          if (result) {
            this.insertMediaFromUpload(result, type);
          } else {
            console.error('文件上传失败:', error);
            notification.error(`上传失败: ${error.message}`);
          }
        }
      );
      
      // 检查是否有成功上传的文件
      const successCount = results.filter(r => r.success).length;
      if (successCount > 0) {
        notification.success(`成功上传 ${successCount} 个文件`);
        setTimeout(closeModal, 1500);
      }
      
    } catch (error) {
      console.error('批量上传失败:', error);
      notification.error('上传失败');
    }
  }

  /**
   * 从上传结果插入媒体
   */
  insertMediaFromUpload(uploadResult, type) {
    const { url, filename, originalFile } = uploadResult;
    
    switch (type) {
      case 'image':
        this.insertHTML(`
          <figure class="media-figure">
            <img src="${url}" alt="${filename}" style="max-width: 100%; height: auto; border-radius: 0.375rem;">
            <figcaption class="text-sm text-neutral-500 text-center mt-2">${filename}</figcaption>
          </figure>
        `);
        break;
        
      case 'video':
        this.insertHTML(`
          <figure class="media-figure">
            <video controls style="max-width: 100%; height: auto; border-radius: 0.375rem;">
              <source src="${url}" type="${originalFile.type}">
              您的浏览器不支持视频播放。
            </video>
            <figcaption class="text-sm text-neutral-500 text-center mt-2">${filename}</figcaption>
          </figure>
        `);
        break;
        
      case 'audio':
        this.insertHTML(`
          <figure class="media-figure">
            <div class="audio-player bg-neutral-50 border border-neutral-200 rounded-lg p-4">
              <div class="flex items-center gap-3 mb-2">
                <i class="fa fa-music text-primary"></i>
                <span class="font-medium text-neutral-700">${filename}</span>
              </div>
              <audio controls class="w-full">
                <source src="${url}" type="${originalFile.type}">
                您的浏览器不支持音频播放。
              </audio>
            </div>
          </figure>
        `);
        break;
    }
  }

  /**
   * 从URL插入媒体
   */
  insertMediaFromUrl(url, type) {
    switch (type) {
      case 'image':
        this.insertHTML(`
          <figure class="media-figure">
            <img src="${url}" alt="图片" style="max-width: 100%; height: auto; border-radius: 0.375rem;">
          </figure>
        `);
        break;
        
      case 'video':
        this.insertHTML(`
          <figure class="media-figure">
            <video controls style="max-width: 100%; height: auto; border-radius: 0.375rem;">
              <source src="${url}">
              您的浏览器不支持视频播放。
            </video>
          </figure>
        `);
        break;
        
      case 'audio':
        this.insertHTML(`
          <figure class="media-figure">
            <div class="audio-player bg-neutral-50 border border-neutral-200 rounded-lg p-4">
              <div class="flex items-center gap-3 mb-2">
                <i class="fa fa-music text-primary"></i>
                <span class="font-medium text-neutral-700">音频文件</span>
              </div>
              <audio controls class="w-full">
                <source src="${url}">
                您的浏览器不支持音频播放。
              </audio>
            </div>
          </figure>
        `);
        break;
    }
  }

  /**
   * 处理文件拖拽
   */
  async handleFileDrop(files) {
    if (files.length === 0) return;
    
    // 初始化媒体上传器
    if (!this.mediaUploader) {
      this.mediaUploader = new MediaUploader();
    }
    
    const fileArray = Array.from(files);
    
    // 按类型分组文件
    const imageFiles = [];
    const videoFiles = [];
    const audioFiles = [];
    const unsupportedFiles = [];
    
    fileArray.forEach(file => {
      const validation = this.mediaUploader.validateFile(file);
      if (validation.valid) {
        switch (validation.type) {
          case 'image':
            imageFiles.push(file);
            break;
          case 'video':
            videoFiles.push(file);
            break;
          case 'audio':
            audioFiles.push(file);
            break;
        }
      } else {
        unsupportedFiles.push({ file, errors: validation.errors });
      }
    });
    
    // 显示不支持的文件错误
    if (unsupportedFiles.length > 0) {
      const errorMessages = unsupportedFiles.map(item => 
        `${item.file.name}: ${item.errors.join(', ')}`
      );
      notification.error(`以下文件不支持:\n${errorMessages.join('\n')}`);
    }
    
    // 上传并插入支持的文件
    const allSupportedFiles = [...imageFiles, ...videoFiles, ...audioFiles];
    if (allSupportedFiles.length > 0) {
      this.updateStatus('上传文件中...');
      
      try {
        const results = await this.mediaUploader.uploadFiles(
          allSupportedFiles,
          (overallProgress) => {
            this.updateStatus(`上传进度: ${Math.round(overallProgress)}%`);
          },
          (result, error) => {
            if (result) {
              this.insertMediaFromUpload(result, result.type);
            } else {
              console.error('文件上传失败:', error);
            }
          }
        );
        
        const successCount = results.filter(r => r.success).length;
        if (successCount > 0) {
          this.updateStatus('文件上传完成');
          notification.success(`成功上传 ${successCount} 个文件`);
        }
        
      } catch (error) {
        console.error('批量上传失败:', error);
        this.updateStatus('上传失败');
        notification.error('文件上传失败');
      }
    }
  }

  /**
   * 插入HTML
   */
  insertHTML(html) {
    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      range.deleteContents();
      
      const div = document.createElement('div');
      div.innerHTML = html;
      
      const fragment = document.createDocumentFragment();
      while (div.firstChild) {
        fragment.appendChild(div.firstChild);
      }
      
      range.insertNode(fragment);
      range.collapse(false);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }

  /**
   * 插入文本
   */
  insertText(text) {
    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      range.deleteContents();
      range.insertNode(document.createTextNode(text));
      range.collapse(false);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }

  /**
   * 处理内容变化
   */
  handleContentChange() {
    this.content = this.editor.innerHTML;
    this.updateCharCount();
    this.updateWordCount();
    this.updatePlaceholder();
    
    // 检查字符限制
    if (this.getTextContent().length > this.options.maxLength) {
      this.updateStatus('字符数超出限制');
      return;
    }
    
    // 触发内容变化事件
    this.dispatchEvent('contentChange', {
      content: this.content,
      text: this.getTextContent()
    });
    
    // 重置自动保存定时器
    if (this.options.autoSave) {
      this.resetAutoSave();
    }
  }

  /**
   * 更新工具栏状态
   */
  updateToolbarState() {
    const buttons = this.toolbar.querySelectorAll('.toolbar-btn');
    
    buttons.forEach(btn => {
      const command = btn.dataset.command;
      let isActive = false;
      
      try {
        switch (command) {
          case 'bold':
          case 'italic':
          case 'underline':
          case 'strikeThrough':
            isActive = document.queryCommandState(command);
            break;
          case 'formatBlock':
            const value = btn.dataset.value;
            isActive = document.queryCommandValue('formatBlock').toLowerCase() === value;
            break;
          case 'insertUnorderedList':
          case 'insertOrderedList':
            isActive = document.queryCommandState(command);
            break;
        }
      } catch (error) {
        // 忽略查询命令状态的错误
      }
      
      if (isActive) {
        btn.classList.add('bg-primary', 'text-white');
      } else {
        btn.classList.remove('bg-primary', 'text-white');
      }
    });
  }

  /**
   * 更新占位符
   */
  updatePlaceholder() {
    const isEmpty = this.editor.textContent.trim() === '';
    
    if (isEmpty) {
      this.editor.classList.add('empty');
      if (!this.editor.dataset.placeholder) {
        this.editor.dataset.placeholder = this.options.placeholder;
      }
    } else {
      this.editor.classList.remove('empty');
    }
  }

  /**
   * 更新字符计数
   */
  updateCharCount() {
    const charCount = this.getTextContent().length;
    const charCountEl = this.container.querySelector('#char-count');
    
    if (charCountEl) {
      charCountEl.textContent = charCount;
      
      // 接近限制时变红
      if (charCount > this.options.maxLength * 0.9) {
        charCountEl.classList.add('text-red-500');
      } else {
        charCountEl.classList.remove('text-red-500');
      }
    }
  }

  /**
   * 更新字数统计
   */
  updateWordCount() {
    const text = this.getTextContent();
    const wordCount = text.length; // 中文按字符计算
    const wordCountEl = this.container.querySelector('#word-count');
    
    if (wordCountEl) {
      wordCountEl.textContent = `${wordCount} 字`;
    }
  }

  /**
   * 更新状态
   */
  updateStatus(status) {
    const statusEl = this.container.querySelector('#editor-status');
    if (statusEl) {
      statusEl.textContent = status;
    }
  }

  /**
   * 获取纯文本内容
   */
  getTextContent() {
    return this.editor.textContent || '';
  }

  /**
   * 获取HTML内容
   */
  getContent() {
    return this.editor.innerHTML;
  }

  /**
   * 设置内容
   */
  setContent(content) {
    this.editor.innerHTML = content;
    this.content = content;
    this.handleContentChange();
    this.saveToHistory();
  }

  /**
   * 清空内容
   */
  clear() {
    this.editor.innerHTML = '';
    this.handleContentChange();
  }

  /**
   * 聚焦编辑器
   */
  focus() {
    this.editor.focus();
  }

  /**
   * 保存到历史记录
   */
  saveToHistory() {
    const content = this.getContent();
    
    // 如果内容没有变化，不保存
    if (this.history[this.historyIndex] === content) {
      return;
    }
    
    // 删除当前位置之后的历史记录
    this.history = this.history.slice(0, this.historyIndex + 1);
    
    // 添加新的历史记录
    this.history.push(content);
    
    // 限制历史记录数量
    if (this.history.length > this.maxHistory) {
      this.history.shift();
    } else {
      this.historyIndex++;
    }
  }

  /**
   * 撤销
   */
  undo() {
    if (this.historyIndex > 0) {
      this.historyIndex--;
      this.setContent(this.history[this.historyIndex]);
      this.updateStatus('已撤销');
    }
  }

  /**
   * 重做
   */
  redo() {
    if (this.historyIndex < this.history.length - 1) {
      this.historyIndex++;
      this.setContent(this.history[this.historyIndex]);
      this.updateStatus('已重做');
    }
  }

  /**
   * 开始自动保存
   */
  startAutoSave() {
    this.autoSaveTimer = setInterval(() => {
      this.save();
    }, this.options.autoSaveInterval);
  }

  /**
   * 重置自动保存定时器
   */
  resetAutoSave() {
    if (this.autoSaveTimer) {
      clearInterval(this.autoSaveTimer);
      this.startAutoSave();
    }
  }

  /**
   * 保存内容
   */
  async save() {
    try {
      this.updateStatus('保存中...');
      
      // 触发保存事件
      const result = await this.dispatchEvent('save', {
        content: this.getContent(),
        text: this.getTextContent()
      });
      
      if (result !== false) {
        this.showAutoSaveStatus();
        this.updateStatus('已保存');
      }
    } catch (error) {
      console.error('保存失败:', error);
      this.updateStatus('保存失败');
    }
  }

  /**
   * 显示自动保存状态
   */
  showAutoSaveStatus() {
    const statusEl = this.container.querySelector('#auto-save-status');
    if (statusEl) {
      statusEl.classList.remove('hidden');
      setTimeout(() => {
        statusEl.classList.add('hidden');
      }, 2000);
    }
  }

  /**
   * 分发事件
   */
  async dispatchEvent(eventName, data) {
    const event = new CustomEvent(`richEditor:${eventName}`, {
      detail: data,
      bubbles: true,
      cancelable: true
    });
    
    this.container.dispatchEvent(event);
    
    // 如果有回调函数，调用它
    const callbackName = `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}`;
    if (typeof this.options[callbackName] === 'function') {
      return await this.options[callbackName](data);
    }
  }

  /**
   * 销毁编辑器
   */
  destroy() {
    if (this.autoSaveTimer) {
      clearInterval(this.autoSaveTimer);
    }
    
    // 移除事件监听器
    // 注意：这里简化处理，实际应该保存引用并移除
    
    this.container.innerHTML = '';
  }
}

// 添加编辑器样式
const editorStyles = `
  .rich-editor .empty::before {
    content: attr(data-placeholder);
    color: #9CA3AF;
    pointer-events: none;
    position: absolute;
  }
  
  .rich-editor #editor-content {
    line-height: 1.6;
    transition: all 0.3s ease;
  }
  
  .rich-editor #editor-content.drag-over {
    background-color: #F0F9FF;
    border: 2px dashed #3B82F6;
    border-radius: 0.5rem;
  }
  
  .rich-editor #editor-content h1 {
    font-size: 1.875rem;
    font-weight: bold;
    margin: 1rem 0 0.5rem 0;
  }
  
  .rich-editor #editor-content h2 {
    font-size: 1.5rem;
    font-weight: bold;
    margin: 1rem 0 0.5rem 0;
  }
  
  .rich-editor #editor-content h3 {
    font-size: 1.25rem;
    font-weight: bold;
    margin: 1rem 0 0.5rem 0;
  }
  
  .rich-editor #editor-content ul,
  .rich-editor #editor-content ol {
    margin: 0.5rem 0;
    padding-left: 1.5rem;
  }
  
  .rich-editor #editor-content li {
    margin: 0.25rem 0;
  }
  
  .rich-editor #editor-content a {
    color: #3B82F6;
    text-decoration: underline;
  }
  
  .rich-editor #editor-content img {
    max-width: 100%;
    height: auto;
    margin: 0.5rem 0;
    border-radius: 0.375rem;
  }
  
  .rich-editor #editor-content blockquote {
    border-left: 4px solid #E5E7EB;
    padding-left: 1rem;
    margin: 1rem 0;
    font-style: italic;
    color: #6B7280;
  }
  
  .rich-editor #editor-content .media-figure {
    margin: 1rem 0;
    text-align: center;
  }
  
  .rich-editor #editor-content .media-figure figcaption {
    margin-top: 0.5rem;
    font-size: 0.875rem;
    color: #6B7280;
  }
  
  .rich-editor #editor-content .audio-player {
    max-width: 400px;
    margin: 1rem auto;
  }
  
  .rich-editor #editor-content video {
    max-width: 100%;
    height: auto;
    border-radius: 0.375rem;
  }
  
  .rich-editor #editor-content audio {
    width: 100%;
  }
  
  /* 媒体插入模态框样式 */
  .upload-area.border-primary {
    border-color: #3B82F6 !important;
    background-color: rgba(59, 130, 246, 0.05);
  }
  
  .btn-primary {
    background-color: #334155;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .btn-primary:hover {
    background-color: rgba(51, 65, 85, 0.9);
  }
  
  .btn-secondary {
    background-color: #E5E7EB;
    color: #374151;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .btn-secondary:hover {
    background-color: #D1D5DB;
  }
  
  /* 手写板样式 */
  .drawing-canvas .tool-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2rem;
    height: 2rem;
    border: 1px solid #D1D5DB;
    border-radius: 0.375rem;
    background-color: white;
    color: #6B7280;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .drawing-canvas .tool-btn:hover {
    background-color: #F3F4F6;
    border-color: #9CA3AF;
  }
  
  .drawing-canvas .tool-btn.active {
    background-color: #334155;
    color: white;
    border-color: #334155;
  }
  
  .drawing-canvas .color-btn {
    width: 1.5rem;
    height: 1.5rem;
    border: 2px solid #D1D5DB;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .drawing-canvas .color-btn:hover {
    transform: scale(1.1);
  }
  
  .drawing-canvas .color-btn.active {
    border-color: #334155;
    box-shadow: 0 0 0 2px rgba(51, 65, 85, 0.2);
  }
  
  .drawing-canvas .btn-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2rem;
    height: 2rem;
    border: none;
    background: none;
    color: #6B7280;
    cursor: pointer;
    border-radius: 0.375rem;
    transition: all 0.2s;
  }
  
  .drawing-canvas .btn-icon:hover {
    background-color: #F3F4F6;
    color: #374151;
  }
  
  .drawing-canvas .btn-icon:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  .drawing-canvas #drawing-canvas {
    border: 1px solid #E5E7EB;
  }
  
  .handwriting-figure {
    border: 1px dashed #D1D5DB;
    padding: 0.5rem;
    background-color: #F9FAFB;
  }
  
  /* 表情选择器样式 */
  .emoji-picker {
    font-family: 'Apple Color Emoji', 'Segoe UI Emoji', 'Noto Color Emoji', sans-serif;
  }
  
  .emoji-picker .category-btn {
    min-width: 2.5rem;
    border: none;
    background: none;
    cursor: pointer;
  }
  
  .emoji-picker .category-btn:hover {
    background-color: #F3F4F6;
  }
  
  .emoji-picker .category-btn.active {
    background-color: #334155 !important;
    color: white !important;
  }
  
  .emoji-picker .emoji-btn {
    border: none;
    background: none;
    cursor: pointer;
    font-family: inherit;
  }
  
  .emoji-picker .emoji-btn:hover {
    background-color: #F3F4F6;
    transform: scale(1.1);
  }
  
  .emoji-picker .emoji-btn:active {
    transform: scale(0.95);
  }
  
  .emoji-picker .emoji-grid::-webkit-scrollbar {
    width: 6px;
  }
  
  .emoji-picker .emoji-grid::-webkit-scrollbar-track {
    background: #F1F5F9;
  }
  
  .emoji-picker .emoji-grid::-webkit-scrollbar-thumb {
    background: #CBD5E1;
    border-radius: 3px;
  }
  
  .emoji-picker .emoji-grid::-webkit-scrollbar-thumb:hover {
    background: #94A3B8;
  }
  
  /* 编辑器中的表情样式 */
  .rich-editor #editor-content .emoji {
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
  }
`;

// 注入样式
if (!document.querySelector('#rich-editor-styles')) {
  const styleEl = document.createElement('style');
  styleEl.id = 'rich-editor-styles';
  styleEl.textContent = editorStyles;
  document.head.appendChild(styleEl);
}

// 导出富文本编辑器
window.RichEditor = RichEditor;